package com.dongjiantong.web.protal.controller.farmrecords;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.redis.RedisUtil;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.dongjiantong.sys.model.AnimalType;
import com.dongjiantong.sys.service.AnimalTypeService;
import com.dongjiantong.user.model.Farms;
import com.dongjiantong.user.model.UserArea;
import com.dongjiantong.user.service.FarmsService;
import com.dongjiantong.user.service.OrgUserAreaService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 养殖档案公用功能--查询(地区,养殖场,畜种...)
 */
@Slf4j
@OpenBean
public class UtilsController {
    @Reference(version = "1.0.3")
    public AnimalTypeService animalTypeService;
    @Reference(version = "1.0.0")
    public FarmsService farmsService;
    @Reference(version = "1.0.0")
    public OrgUserAreaService orgUserAreaService;

    /**
     * web获取畜种
     * @param pid 上级id
     * @param regionAccountId 所属市id
     */
    @OpenMethod(key = "web.farmrecords.obtainAnimalType",
                            paramNames = {"pid","regionAccountId"},
                            httpMethods = RequestMethod.GET)
    public Response<List> obtainAnimalType(@RequestParam(required = false) Long pid,
                                           @RequestParam(required = false) Long regionAccountId){
        try {
            String key = "FarmRecords:ObtainAnimalType";
            List animalTypeRedisList = RedisUtil.getList(key);
            if (animalTypeRedisList != null && animalTypeRedisList.size() > 0){
                return Response.ok(animalTypeRedisList);
            }

            if (pid == null){
                pid = 0L;
            }
            if (regionAccountId == null){
                regionAccountId = 0L;
            }

            //树形结构遍历动物种类
            List list = this.animalTypeTreeNode(pid,regionAccountId);

            //RedisUtil.setList(key,list);
            return Response.ok(list);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 树形结构遍历动物种类
     * @param pid   父级id
     * @param regionAccountId 地区id
     * @return
     */
    public List animalTypeTreeNode(Long pid,Long regionAccountId) {
        try {
            if (animalTypeService == null){
                throw new OPServerException("animalTypeService 为null,请检查");
            }
            List<AnimalType> animalTypeList = animalTypeService.queryTreeAnimalType(pid, regionAccountId);
            List list = null;
            if (animalTypeList.size() > 0) {
                list = Lists.newArrayList();
                for (AnimalType animalType : animalTypeList) {
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("value", animalType.getAnimalCode());
                    map.put("label", animalType.getAnimalName());
                    map.put("children", animalTypeTreeNode(animalType.getId(), regionAccountId));
                    list.add(map);
                }
            }
            return list;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * web获取地区
     */
    @OpenMethod(key = "web.farmrecords.obtainArea",
            paramNames = {},
            httpMethods = RequestMethod.GET)
    public Response<List> obtainArea(){
        try {
            if (orgUserAreaService == null){
                throw new OPServerException("orgUserAreaService 为null,请检查");
            }
            Long userId = UserUtil.getUserId();
            if (userId == null){
                throw new OPServerException(HttpCode.UNAUTHORIZED,"对不起,您无权查看,请登陆后重试");
            }
            List list = orgUserAreaService.queryLocationArea(userId);
            if (list == null && list.size() == 0){
                return Response.fail("查无数据");
            }
            return Response.ok(list);
        } catch (OPServerException e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * web获取养殖场
     * @param areaList 传入的地区code (省,市,县..)list
     * @return
     */
    @OpenMethod(key = "web.farmrecords.obtainFarms",
            paramNames = {"areaList"},
            httpMethods = RequestMethod.GET)
    public Response<List> obtainFarms(@RequestParam (required = false) List<Integer> areaList) {
        if (orgUserAreaService == null){
            throw new OPServerException("orgUserAreaService 为null,请检查");
        }
        if (farmsService == null){
            throw new OPServerException("farmsService 为null,请检查");
        }
        Long userId = UserUtil.getUserId();
        if (userId == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST, "请登录后确认您的身份后重试");
        }

        String key = null;
        List list = null;
        // 如果传入的地区code不为空
        if (areaList != null) {

            //获取当前登陆人的最高管辖级别
            int level = -1;
            List<UserArea> userAreaList = orgUserAreaService.queryByUserId(userId);
            boolean isProvince = userAreaList.stream().filter(city -> 0 == city.getCityId()).collect(Collectors.toList()).size() != 0;
            boolean isCity = userAreaList.stream().filter(region -> 0 == region.getRegionId()).collect(Collectors.toList()).size() != 0;
            boolean isRegion = userAreaList.stream().filter(street -> 0 == street.getStreetId()).collect(Collectors.toList()).size() != 0;
            boolean isStreet = userAreaList.stream().filter(village -> 0 == village.getVillageId()).collect(Collectors.toList()).size() != 0;
            if (isProvince) {
                level = 1;//省级
            } else if (isCity) {
                level = 2;//市级
            } else if (isRegion) {
                level = 3;//县级
            } else if (isStreet) {
                level = 4;//镇级
            } else {
                level = 5;//村级
            }

            //判断传入数组的长度(传入数组长度与对应的管辖级别比对[省级对应的数组长度为1,市对应数组长度为2,县==>3,  镇==>4,  村==>5])
            int areaListSize = areaList.size();
            if (areaListSize < level) {
                //查询范围超出管辖级别,查询登录人默认管辖的区域
                //根据当前登录人id获取其管辖区域内的养殖场
                List<Farms> farmsLists = farmsService.selectByUserId(userId);
                if (farmsLists.size() > 0) {
                    list = Lists.newArrayList();
                    for (Farms farms : farmsLists) {
                        Map map = Maps.newHashMap();
                        map.put("value", farms.getId());
                        map.put("label", farms.getFarmsname());
                        list.add(map);
                    }
                }
            } else {
                //取出地区code,根据code查询其区域下的养殖场
                Integer provinceId = null, cityId = null, regionId = null, streetId = null, villageId = null;
                int listSize = areaList.size();
                switch (listSize){
                    case 1:
                        provinceId = areaList.get(0);
                        break;
                    case 2:
                        provinceId = areaList.get(0);
                        cityId = areaList.get(1);
                        break;
                    case 3:
                        provinceId = areaList.get(0);
                        cityId = areaList.get(1);
                        regionId = areaList.get(2);
                        break;
                    case 4:
                        provinceId = areaList.get(0);
                        cityId = areaList.get(1);
                        regionId = areaList.get(2);
                        streetId = areaList.get(3);
                        break;
                    case 5:
                        provinceId = areaList.get(0);
                        cityId = areaList.get(1);
                        regionId = areaList.get(2);
                        streetId = areaList.get(3);
                        villageId = areaList.get(4);
                        break;
                    default:
                        break;
                }

                //根据区域编号和当前登陆人查询其区域范围内的养殖场
                List<Farms> farmsList = farmsService.selectByArea(userId,provinceId,cityId,regionId,streetId,villageId,1);
                if (farmsList.size() > 0){
                    list = Lists.newArrayList();
                    for (Farms farms : farmsList) {
                        Map map = Maps.newHashMap();
                        map.put("value", farms.getId());
                        map.put("label", farms.getFarmsname());
                        list.add(map);
                    }
                }
            }
        } else {

            //redis查找
            key = "FarmRecords:ObtainFarms.paramAreaCodeNull.userId=" + userId;
            List list1 = RedisUtil.getList(key);
            if (list1 != null && list1.size() > 0) {
                return Response.ok(list1);
            }

            //根据当前登录人id获取其管辖区域内的养殖场
            List<Farms> farmsLists = farmsService.selectByUserId(userId);
            if (farmsLists.size() > 0) {
                list = Lists.newArrayList();
                for (Farms farms : farmsLists) {
                    Map map = Maps.newHashMap();
                    map.put("value", farms.getId());
                    map.put("label", farms.getFarmsname());
                    list.add(map);
                }
            }
        }
        return Response.ok(list);
    }
}
